import requests


def get_binance_server_time():
    url = "https://api.binance.com/api/v3/time"
    response = requests.get(url)
    if response.status_code == 200:
        server_time = response.json()['serverTime']
        return server_time
    else:
        raise Exception("无法获取币安服务器时间")


class SpotTrader:
    """仅使用现货交易权限的交易类"""

    def __init__(self, api_key, api_secret, testnet=True):
        self.api_key = api_key
        self.api_secret = api_secret
        self.base_url = "https://testnet.binance.vision" if testnet else "https://api.binance.com"

    def spot_trade(self, symbol, side, quantity, price=None, order_type="LIMIT"):
        """执行现货交易"""
        import requests
        import hmac
        import hashlib
        import time

        endpoint = "/api/v3/order"
        # timestamp = int(time.time() * 1000)
        timestamp = get_binance_server_time()

        # 构建基本参数
        params = f"symbol={symbol}&side={side}&type={order_type}&quantity={quantity}"

        # 如果是限价单，添加价格参数
        if order_type == "LIMIT" and price:
            params += f"&timeInForce=GTC&price={price}"

        params += f"&timestamp={timestamp}&recvWindow=5000"

        # 创建签名
        signature = hmac.new(
            self.api_secret.encode('utf-8'),
            params.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()

        url = f"{self.base_url}{endpoint}?{params}&signature={signature}"
        headers = {"X-MBX-APIKEY": self.api_key}

        try:
            response = requests.post(url, headers=headers, timeout=10)
            return response.json()
        except Exception as e:
            return {"error": str(e)}

    def get_spot_balance(self, asset="USDT"):
        """获取现货账户余额"""
        import requests
        import hmac
        import hashlib
        import time

        endpoint = "/api/v3/account"
        timestamp = int(time.time() * 1000)

        params = f"timestamp={timestamp}&recvWindow=5000"
        signature = hmac.new(
            self.api_secret.encode('utf-8'),
            params.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()

        url = f"{self.base_url}{endpoint}?{params}&signature={signature}"
        headers = {"X-MBX-APIKEY": self.api_key}

        try:
            response = requests.get(url, headers=headers, timeout=10)
            data = response.json()

            if 'balances' in data:
                for balance in data['balances']:
                    if balance['asset'] == asset:
                        return balance
            return None
        except Exception as e:
            print(f"获取余额失败: {e}")
            return None

API_KEY = "oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V"
API_SECRET = "8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN"
# 使用示例
trader = SpotTrader(API_KEY, API_SECRET, testnet=False)

# 购买BNB
result = trader.spot_trade("BNBUSDT", "BUY", "0.01", "500", "LIMIT")
print("交易结果:", result)

# 检查余额
balance = trader.get_spot_balance("BNB")
print("BNB余额:", balance)